﻿using MediatR;
using S.PurchaseAndSales.Domain.Dto;
using S.PurchaseAndSales.Domain.Enum;
using S.PurchaseAndSales.Domain.Model;
using S.PurchaseAndSales.Infrastructure.Interface.PurchaseForm;
using S.PurchaseAndSales.Read.Api.Application.Command.PurchaseFormCommand;
using S.PurchaseAndSales.Read.Api.Dto;

namespace S.PurchaseAndSales.Read.Api.Application.CommandHandlers.PurchaseFormHandler
{
    /// <summary>
    /// 采购表分页显示
    /// </summary>
    public class PurchaseFormGetPagerCommandHandler : IRequestHandler<PurchaseFormGetPagerCommand, Pager<GetPurchaseFormDto>>
    {
        #region 注入
        private readonly IPurchaseFormRepository repository;

        public PurchaseFormGetPagerCommandHandler(IPurchaseFormRepository repository)
        {
            this.repository = repository;
        }
        #endregion
        public async Task<Pager<GetPurchaseFormDto>> Handle(PurchaseFormGetPagerCommand request, CancellationToken cancellationToken)
        {/*(request.CreateBy,request.CreateDate,request.SummaryEnum,request.Warehouse,request.BuildingId);*/
            List<GetPurchaseFormDto> list=(await repository.GetPurchaseFormModel()).Where(x => (string.IsNullOrEmpty(request.CreateBy) || x.CreateBy == request.CreateBy) && (string.IsNullOrEmpty(request.CreateDate) || x.CreateTime >= DateTime.Parse(request.CreateDate)) && (string.IsNullOrEmpty(request.CreateDate) || x.CreateTime < DateTime.Parse(request.CreateDate).AddDays(1)) && (request.SummaryEnum == 0 || x.SummaryEnum == (SummaryEnum)request.SummaryEnum) && (string.IsNullOrEmpty(request.Warehouse) || x.Warehouse.Contains(request.Warehouse))&& (request.BuildingId == 0 || x.BuildingId == request.BuildingId)).ToList();
            int totalCount=list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            list = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return new Pager<GetPurchaseFormDto> { 
                PageCount = pageCount,
                TotalCount=totalCount,
                ResultData=list
            };
        }
    }
}
